﻿using MiniFox.Components;
using MiniFox.Infrastructure;
using MiniFox.Platform.Applications.Auth;
using MiniFox.Platform.Exceptions;
using MiniFox.Utility;
using Repository.Core.Models.Dto;
using Repository.Core.Models.Queries;
using Repository.Core.Models.VO;
using Repository.Core.Providers;

namespace Repository.Core.Services.Impls
{
    [AutoResolve]
    public class PublishService : VersioningServiceBase, IPublishService
    {
        [AutoWired]
        protected IPublishProvider Provider { get; set; }

        public PublishService(string repoName, SystemPrincipal principal) : base(repoName, principal)
        {
        }

        public ResultObject<IEnumerable<PublishVo>> Query(PagedQueryObject<CommonQuery> request)
        {
            ResultObject<IEnumerable<PublishVo>> result = Provider.Query(this.RepoName, request);
            return result;
        }

        public void Publish(PublishDto request)
        {
            this.Publish(request.VersionSetName, request.VersionID);
        }

        public void Publish(string versionSetName, long? versionId)
        {
            if (!this.Provider.Publish(this.RepoName, this.Identity, versionSetName, versionId))
                throw new PlatformException("ERR_OperateFail");
        }

        public object GetItemContent(string versionSetName)
        {
            var content = this.Provider.GetItemContent(this.RepoName, versionSetName);
            if (content == null) return null;
            return content.ToJsonObject();
        }

        public virtual T GetItemObject<T>(string versionSetName)
        {
            var content = Provider.GetItemContent(this.RepoName, versionSetName);
            return content.ToJsonObject<T>();
        }
    }
}
